﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.interfaces;
using System.Xml;

namespace uQR.PackageActions
{
    public class AddUrlRewriteRule : IPackageAction
    {
        // Namespace that is used by urlrewriting.net
        private const string NAMESPACE_URI = "http://www.urlrewriting.net/schemas/config/2006/07";

        #region IPackageAction Members

        public string Alias()
        {
            return "uQR_AddUrlRewriteRule";
        }

        public bool Execute(string packageName, XmlNode xmlData)
        {
            //Set result default to false
            bool result = false;

            //Check if the xmlData has a childnode (the xml rule node)
            if (xmlData.HasChildNodes)
            {
                //Select RewriteRuleNode from the supplied xmlData
                XmlNode rewriteData = xmlData.SelectSingleNode("./add");

                //Get the rule name
                string rewriteRuleName = rewriteData.Attributes["name"].Value;

                //Open the URL Rewrite config file
                XmlDocument rewriteFile = umbraco.xmlHelper.OpenAsXmlDocument("/config/UrlRewriting.config");

                //Initialize a namespace Manager that adds the namespaces to the umbracoSettingsFile Xml Document 
                XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(rewriteFile.NameTable);
                xmlnsManager.AddNamespace("urlrewritingnet", NAMESPACE_URI);
                xmlnsManager.AddNamespace("", NAMESPACE_URI);

                //Select rewrites node in the config file and append the importNode
                XmlNode rewriteRootNode = rewriteFile.SelectSingleNode("//urlrewritingnet:rewrites", xmlnsManager);

                //Check to see if a rule with the same name already exists
                if (rewriteRootNode.SelectSingleNode("urlrewritingnet:add[@name = '" + rewriteRuleName + "']", xmlnsManager) == null)
                {
                    //Create a new Rewrite rule node 
                    XmlNode newRewriteRuleNode = (XmlNode)rewriteFile.CreateElement("add", NAMESPACE_URI);

                    //Copy all attributes from the package xml to the new Rewrite rule node
                    foreach (XmlAttribute att in rewriteData.Attributes)
                    {
                        XmlAttribute attribute = rewriteFile.CreateAttribute(att.Name);
                        attribute.Value = att.Value;
                        newRewriteRuleNode.Attributes.Append(attribute);
                    }

                    //Append the new rewrite rule node to the Rewrite config file
                    rewriteRootNode.AppendChild(newRewriteRuleNode);

                    //Save the Rewrite config file with the new rewerite rule
                    rewriteFile.Save(System.Web.HttpContext.Current.Server.MapPath("/config/UrlRewriting.config"));

                    //No errors so the result is true
                    result = true;
                }
            }
            return result;
        }

        public bool Undo(string packageName, System.Xml.XmlNode xmlData)
        {
            bool result = false;

            //Check if the xmlData has a childnode (the xml rule node)
            if (xmlData.HasChildNodes)
            {
                //Get the rewrite rule xml node from the supplied xmlData node
                XmlNode rewriteData = xmlData.SelectSingleNode("//add");

                //Get the rule name
                string rewriteRuleName = rewriteData.Attributes["name"].Value;

                //Open the url Rewrite config file
                XmlDocument rewriteFile = umbraco.xmlHelper.OpenAsXmlDocument("/config/UrlRewriting.config");

                //Initialize a namespace Manager that adds the namespaces to the umbracoSettingsFile Xml Document
                XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(rewriteFile.NameTable);
                xmlnsManager.AddNamespace("urlrewritingnet", NAMESPACE_URI);
                xmlnsManager.AddNamespace("", NAMESPACE_URI);

                //Select the rootnode where we want to delete from
                XmlNode rewriteRootNode = rewriteFile.SelectSingleNode("//urlrewritingnet:rewrites", xmlnsManager);

                //Select the url rewrite rule by name from the config file
                XmlNode rewriteRule = rewriteRootNode.SelectSingleNode("urlrewritingnet:add[@name = '" + rewriteRuleName + "']", xmlnsManager);
                if (rewriteRule != null)
                {
                    //Rule is found, remove it from the xml document
                    rewriteRootNode.RemoveChild(rewriteRule);
                    //Save the modified configuration file
                    rewriteFile.Save(System.Web.HttpContext.Current.Server.MapPath("/config/UrlRewriting.config"));
                }
                result = true;
            }
            return result;
        }

        public XmlNode SampleXml()
        {
            throw new NotImplementedException();
        }

        #endregion

    }
}